<template>
  <van-nav-bar :title="id ? '编辑地址' : '新增地址'" left-text="返回">
    <template #left>
      <van-icon name="arrow-left" size="18" @click="$router.back()" />
    </template>
    <template #right>
      <van-icon name="ellipsis" size="18" />
    </template>
  </van-nav-bar>
  <van-address-edit
    :area-list="areaList"
    :show-delete="id ? true : false"
    show-set-default
    :address-info="info"
    :area-columns-placeholder="['请选择', '请选择', '请选择']"
    @save="onSave"
    @delete="onDelete"
  />
</template>
<script setup>
import { areaList } from "@vant/area-data";
import { addAddress, getAddressDetail, updateAddress,removeAddress } from "@/api/index.js";
import { showSuccessToast } from "vant";
import { useRouter, useRoute } from "vue-router";
import { ref } from "vue";
let router = useRouter();
let route = useRoute();
let id = route.query.productId;
let info = ref({});

//根据地址获取地址编码
let getAreaCode = (area) => {
  area = area.replace(/区|县/, "");
  for (let k in areaList.county_list) {
    if (areaList.county_list[k].includes(area)) {
      return k;
    }
  }
};
//编辑数据回显
let geteditdata = async () => {
  getAddressDetail(id).then((res) => {
    let { data } = res;
    info.value = {
      id:data.addressId,
      name: data.userName,
      tel: data.userPhone,
      province: data.provinceName,
      city: data.cityName,
      county: data.regionName,
      addressDetail: data.detailAddress,
      areaCode: getAreaCode(data.regionName),
      isDefault: data.defaultFlag ? true : false,
    };
  });
};

if (id) {
  geteditdata();
}

//编辑数据回显

//点击保存
let onSave = (obj) => {
  let options = {
    areaCode: obj.areaCode,
    cityName: obj.city,
    defaultFlag: obj.isDefault ? 1 : 0,
    detailAddress: obj.addressDetail,
    postalCode: getAreaCode(obj.county),
    provinceName: obj.province,
    regionName: obj.county,
    userName: obj.name,
    userPhone: obj.tel,
  };
  if (id) {
    updateAddress({ ...options, addressId: id }).then((res) => {
      if (res.resultCode == 200) {
        showSuccessToast("编辑地址成功");
        setTimeout(() => {
          router.back();
        }, 500);
      }
    });
  } else {
    addAddress({ ...options }).then((res) => {
      if (res.resultCode == 200) {
        showSuccessToast("添加地址成功");
        setTimeout(() => {
          router.back();
        }, 500);
      }
    });
  }
};
//点击删除
let onDelete = (item) => {
    removeAddress(item.id).then(res=>{
        if (res.resultCode == 200) {
        showSuccessToast("删除地址成功");
        setTimeout(() => {
          router.back();
        }, 500);
      }
    })
};
</script>
